/**
 *
 */
import OSS;
import OpenPlatform;
import OSSUtil;
import FileForm;
import OpenApi;
import OpenApi.OpenApiUtil;

extends OpenApi;


init(config: OpenApiUtil.Config){
  super(config);
  @endpointRule = 'regional';
  
  checkConfig(config);
  @endpoint = getEndpoint('videoseg', @regionId, @endpointRule, @network, @suffix, @endpointMap, @endpoint);
}

function getEndpoint(productId: string, regionId: string, endpointRule: string, network: string, suffix: string, endpointMap: map[string]string, endpoint: string) throws: string{
  if (!$isNull(endpoint)) {
    return endpoint;
  }
  
  if (!$isNull(endpointMap) && !$isNull(endpointMap[regionId])) {
    return endpointMap[regionId];
  }
  return OpenApiUtil.getEndpointRules(productId, regionId, endpointRule, network, suffix);
}

model GetAsyncJobResultRequest {
  jobId?: string(name='JobId', description='This parameter is required.', example='E75FE679-0303-4DD1-8252-1143B4FA8A27'),
}

model GetAsyncJobResultResponseBody = {
  data?: {
    errorCode?: string(name='ErrorCode', example='InvalidParameter'),
    errorMessage?: string(name='ErrorMessage', example='paramsIllegal'),
    jobId?: string(name='JobId', example='49E2CC28-ED1D-4CC5-854D-7D0AE2B20976'),
    result?: string(name='Result', example='{\\\\"VideoUrl\\\\":\\\\"http://algo-app-aic-vd-cn-shanghai-prod.oss-cn-shanghai.aliyuncs.com/film-summary/49E2CC28-ED1D-4CC5-854D-7D0AE2B20976_rf8mv0.mp4?Expires=1585111875&OSSAccessKeyId=LTAI4FoLmvQ9urWXgSRp****&Signature=7uE0ppt6uwkdwAFz73PPZN4KG7****\\\\"}'),
    status?: string(name='Status', example='PROCESS_SUCCESS'),
  }(name='Data'),
  requestId?: string(name='RequestId', example='6BD843FB-E7B9-45B6-ADE1-9AB1FF450148'),
}

model GetAsyncJobResultResponse = {
  headers?: map[string]string(name='headers'),
  statusCode?: int32(name='statusCode'),
  body?: GetAsyncJobResultResponseBody(name='body'),
}

/**
 * @param request GetAsyncJobResultRequest
 * @param runtime runtime options for this request RuntimeOptions
 * @return GetAsyncJobResultResponse
 */
async function getAsyncJobResultWithOptions(request: GetAsyncJobResultRequest, runtime: $RuntimeOptions): GetAsyncJobResultResponse {
  request.validate();
  var body : map[string]any = {};
  if (!$isNull(request.jobId)) {
    body['JobId'] = request.jobId;
  }
  var req = new OpenApiUtil.OpenApiRequest{ 
    body = OpenApiUtil.parseToMap(body),
  };
  var params = new OpenApiUtil.Params{
    action = 'GetAsyncJobResult',
    version = '2020-03-20',
    protocol = 'HTTPS',
    pathname = '/',
    method = 'POST',
    authType = 'AK',
    style = 'RPC',
    reqBodyType = 'formData',
    bodyType = 'json',
  };
  return callApi(params, req, runtime);
}

/**
 * @param request GetAsyncJobResultRequest
 * @return GetAsyncJobResultResponse
 */
async function getAsyncJobResult(request: GetAsyncJobResultRequest): GetAsyncJobResultResponse {
  var runtime = new $RuntimeOptions{};
  return getAsyncJobResultWithOptions(request, runtime);
}

model SegmentVideoBodyRequest {
  videoUrl?: string(name='VideoUrl', description='This parameter is required.', example='http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/videoseg/SegmentVideoBody/SegmentVideoBody1.mp4'),
}

model SegmentVideoBodyAdvanceRequest {
  videoUrlObject?: readable(name='VideoUrl', description='This parameter is required.', example='http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/videoseg/SegmentVideoBody/SegmentVideoBody1.mp4'),
}

model SegmentVideoBodyResponseBody = {
  data?: {
    videoUrl?: string(name='VideoUrl', example='http://algo-app-aic-vd-cn-shanghai-prod.oss-cn-shanghai.aliyuncs.com/video-human-segmentation/D86DDFBC-B8ED-4780-9E6A-E5BA98D7CC9F.mp4?Expires=1584709406&OSSAccessKeyId=LTAI4FoLmvQ9urWXgSRp****&Signature=Fx5HVxvRjAMIjWL2OvhTlOO4cC****'),
  }(name='Data'),
  message?: string(name='Message'),
  requestId?: string(name='RequestId', example='49E2CC28-ED1D-4CC5-854D-7D0AE2B20976'),
}

model SegmentVideoBodyResponse = {
  headers?: map[string]string(name='headers'),
  statusCode?: int32(name='statusCode'),
  body?: SegmentVideoBodyResponseBody(name='body'),
}

/**
 * @param request SegmentVideoBodyRequest
 * @param runtime runtime options for this request RuntimeOptions
 * @return SegmentVideoBodyResponse
 */
async function segmentVideoBodyWithOptions(request: SegmentVideoBodyRequest, runtime: $RuntimeOptions): SegmentVideoBodyResponse {
  request.validate();
  var body : map[string]any = {};
  if (!$isNull(request.videoUrl)) {
    body['VideoUrl'] = request.videoUrl;
  }
  var req = new OpenApiUtil.OpenApiRequest{ 
    body = OpenApiUtil.parseToMap(body),
  };
  var params = new OpenApiUtil.Params{
    action = 'SegmentVideoBody',
    version = '2020-03-20',
    protocol = 'HTTPS',
    pathname = '/',
    method = 'POST',
    authType = 'AK',
    style = 'RPC',
    reqBodyType = 'formData',
    bodyType = 'json',
  };
  return callApi(params, req, runtime);
}

/**
 * @param request SegmentVideoBodyRequest
 * @return SegmentVideoBodyResponse
 */
async function segmentVideoBody(request: SegmentVideoBodyRequest): SegmentVideoBodyResponse {
  var runtime = new $RuntimeOptions{};
  return segmentVideoBodyWithOptions(request, runtime);
}

async function segmentVideoBodyAdvance(request: SegmentVideoBodyAdvanceRequest, runtime: $RuntimeOptions): SegmentVideoBodyResponse {
  // Step 0: init client
  var accessKeyId = @credential.getAccessKeyId();
  var accessKeySecret = @credential.getAccessKeySecret();
  var securityToken = @credential.getSecurityToken();
  var credentialType = @credential.getType();
  var openPlatformEndpoint = @openPlatformEndpoint;
  if($isNull(openPlatformEndpoint)) {
    openPlatformEndpoint ='openplatform.aliyuncs.com';
  }
  if($isNull(credentialType)) {
    credentialType ='access_key';
  }
  var authConfig = new OpenApiUtil.Config{
    accessKeyId = accessKeyId,
    accessKeySecret = accessKeySecret,
    securityToken = securityToken,
    type = credentialType,
    endpoint = openPlatformEndpoint,
    protocol = @protocol,
    regionId = @regionId,
  };
  var authClient = new OpenPlatform(authConfig);
  var authRequest = new OpenPlatform.AuthorizeFileUploadRequest{
    product = 'videoseg',
    regionId = @regionId,
  };
  var authResponse = new OpenPlatform.AuthorizeFileUploadResponse{};
  var ossConfig = new OSS.Config{
    accessKeyId = accessKeyId,
    accessKeySecret = accessKeySecret,
    type = 'access_key',
    protocol = @protocol,
    regionId = @regionId,
  };
  var ossClient : OSS = new OSS(ossConfig);

  var fileObj = new FileForm.FileField{};
  var ossHeader = new OSS.PostObjectRequest.header{};
  var uploadRequest = new OSS.PostObjectRequest{};
  var ossRuntime = new OSSUtil.RuntimeOptions{};
  OpenApiUtil.convert(runtime, ossRuntime);
  var segmentVideoBodyReq = new SegmentVideoBodyRequest{};
  OpenApiUtil.convert(request, segmentVideoBodyReq);

  if(!$isNull(request.videoUrlObject)) {
    authResponse = authClient.authorizeFileUploadWithOptions(authRequest, runtime);
    ossConfig.accessKeyId = authResponse.body.accessKeyId;
    ossConfig.endpoint = OpenApiUtil.getEndpoint(authResponse.body.endpoint, authResponse.body.useAccelerate, @endpointType);
    ossClient = new OSS(ossConfig);

    fileObj = new FileForm.FileField{
      filename = authResponse.body.objectKey,
      content = request.videoUrlObject,
      contentType = '',
    };
    ossHeader = new OSS.PostObjectRequest.header{
      accessKeyId = authResponse.body.accessKeyId,
      policy = authResponse.body.encodedPolicy,
      signature = authResponse.body.signature,
      key = authResponse.body.objectKey,
      file = fileObj,
      successActionStatus = '201',
    };
    uploadRequest = new OSS.PostObjectRequest{
      bucketName = authResponse.body.bucket,
      header = ossHeader,
    };
    ossClient.postObject(uploadRequest, ossRuntime);
    segmentVideoBodyReq.videoUrl = `http://${authResponse.body.bucket}.${authResponse.body.endpoint}/${authResponse.body.objectKey}`;
  }
  var segmentVideoBodyResp = segmentVideoBodyWithOptions(segmentVideoBodyReq, runtime);
  return segmentVideoBodyResp;
}

